package com.sxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxy.controller.common.R;
import com.sxy.pojo.Employee;
import com.sxy.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @author 宋鑫宇
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param e
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee e) {
        //1.将页面提交的密码进行MD5加密
        String password = e.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, e.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3.如果没有查询到employee对象则返回登陆失败结果
        if (emp == null) {
            return R.error("登陆失败");
        }

        //4.如果查询到对象则进行密码比对
        if (!(emp.getPassword().equals(password))) {
            return R.error("用户名或密码错误");
        }

        //5.如果密码比对成功则查看员工状态是否可用
        if (emp.getStatus() == 0) {
            return R.error("此账号已被禁用");
        }

        //6.确定可以登陆成功,将用户id放到session中，并返回登陆成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理session中保存的当前登录的员工信息
        request.getSession().removeAttribute("employee");
        return R.success("退出登录");
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工信息:{}", employee);
        //设置初始密码,并进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
        //记录用户的创建时间
        //employee.setCreateTime(LocalDateTime.now());
        //设置用户更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //设置此用户由谁来创建,从session中获取id
        //Long empId = (Long) request.getSession().getAttribute("employee");
        //employee.setCreateUser(empId);
        //设置最后的更新人
        //employee.setUpdateUser(empId);

        //调用数据库方法
        employeeService.save(employee);
        return R.success("员工创建成功");
    }

    /**
     * 员工信息分页查询功能
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> getByPage(int page, int pageSize, String name) {
        log.info("page = {},pageSize = {},name = {}", page, pageSize, name);
        //创建分页对象
        Page pageInfo = new Page(page, pageSize);
        //创建条件查询对象
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件,当name!=null时添加此条件，否则不添加
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件,通过UpdateTime排序
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改员工
     *
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info(employee.toString());

        //设置更新时间
        //employee.setUpdateTime(LocalDateTime.now());
        //设置更新的用户
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);
        //执行方法
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("根据员工id " + id);
        //调用service层查询方法
        Employee employee = employeeService.getById(id);
        if (employee == null){
            return R.error("没有找到此员工");
        }
        return R.success(employee);
    }
}
